#@adminLayout() #define main()
<script src="#(ctx)/static/antvx6/js/x6.js" type="text/javascript"></script>
<script src="#(ctx)/static/antvx6/js/x6-node.js" type="text/javascript"></script>
<style>
    .form-horizontal .form-group{
        margin-left: 0px; margin-right: 0px;
    }
</style>
<body>
<div class="ui-layout-north">
    <div id="toolbar">
        <button class="btn btn-sm btn-primary" onclick="saveJson()"><i class="fa fa-save"></i> 保存</button>
        <button class="btn btn-sm btn-primary" onclick="before()"><i class="fa fa-undo"></i> 撤销</button>
        <button class="btn btn-sm btn-primary" onclick="next()"><i class="fa fa-repeat"></i> 重做</button>
        <button class="btn btn-sm btn-primary" onclick="savePng()"><i class="fa fa-file-image-o"></i> 保存png</button>
    </div>
</div>
<div class="ui-layout-west">
    <div id="stencil"></div>
</div>
<div class="ui-layout-center">
    <div id="graph-container" style="width: 100%;height: 100%"></div>
</div>
<div class="ui-layout-east">
        <div class="row" style="margin-left: 0px; margin-right: 0px;">
            <form class="form-horizontal m-t" id="commentForm">
                <div class="form-group">
                    <label class="col-sm-4 control-label">节点名：</label>
                    <div class="col-sm-8">
                        <input type="hidden" name="id" id="node_id"/>
                        <input name="name" id="node_name" class="form-control" readonly>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-4 control-label">类型：</label>
                    <div class="col-sm-8">
                        <input name="shape" class="form-control"  readonly>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-4 control-label" >处理发回：</label>
                    <div class="col-sm-8">
                        <select name="deal_back" class="form-control">
                            <option value="0">不允许发回</option>
                            <option value="1">发回开始</option>
                            <option value="2">发回上一步</option>
                            <option value="3">发回任意</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-4 control-label" title="当前节点未审批时，是否允许上一审批人撤回">是否可撤回：</label>
                    <div class="col-sm-8">
                        <select name="is_back" class="form-control">
                            <option value="0">否</option>
                            <option value="1">是</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-4 control-label" title="">是否可作废：</label>
                    <div class="col-sm-8">
                        <select name="is_cancel" class="form-control">
                            <option value="0">否</option>
                            <option value="1">是</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-4 control-label">处理类型：</label>
                    <div class="col-sm-8">
                        <select name="deal_type" id="deal_type" class="form-control"
                                onchange="dealTypeSelect(this.options[this.options.selectedIndex].value)">
                            <option value="0">单人审批</option>
                            <option value="1">会签审批</option>
                            <option value="2">审批占比</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-4 control-label" title="比例取整数，四舍五入">处理比例(%)：</label>
                    <div class="col-sm-8">
                        <input type="number" class="form-control" name="deal_type_rate" id="deal_type_rate" value="50" disabled/>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-4 control-label">节点属性：</label>
                    <div class="col-sm-8">
                        <select name="deal_attr" class="form-control">
                            <option value="0">自动节点</option>
                            <option value="1">人工节点</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-4 control-label">节点参与组：</label>
                    <div class="col-sm-8">
                        <select name="by_group" class="form-control" id="by_group">
                            <option value="0">无【自批】</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-4 control-label">处理页面：</label>
                    <div class="col-sm-8">
                        <input type="text" class="form-control" name="detail_url" maxlength="40" placeholder="可空"/>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-4 control-label">APP端页面：</label>
                    <div class="col-sm-8">
                        <input type="text" class="form-control" name="app_url" maxlength="40" placeholder="可空"/>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-4 control-label">处理类：</label>
                    <div class="col-sm-8">
                        <input type="text" class="form-control" name="deal_action" maxlength="40" placeholder="可空"/>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-4 control-label" title="过滤下一节点范围的人员">人员过滤：</label>
                    <div class="col-sm-8">
                        <select name="is_filter" class="form-control" id="is_filter">
                            <option value="0">全部人员</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-4 control-label" title="">节点转移：</label>
                    <div class="col-sm-8">
                        <a class="form-control" style="border: none;color: #1a7bb9; text-underline: #1a7bb9" href="javascript:void(0)" onclick="openCond()">节点转移条件及主表赋值</a>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-12">
                        <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存</button>&nbsp;
                    </div>
                </div>
            </form>
        </div>
</div>


<script>
    var id="#(id)";
    var prefix ="#(ctx)/jwflow";

    $(function () {
        var panehHidden = false;
        if ($(this).width() < 769) {
            panehHidden = true;
        }
        $('body').layout({initClosed: panehHidden, west__size: 185, east__size: 350});

    });
    // #region 初始化画布
    const graph = new X6.Graph({
        container: document.getElementById('graph-container'),
        width: 1800,
        height: 1000,
        grid: true,
        mousewheel: {       //按住 ctrl键鼠标滚轮控制放大缩小
            enabled: true,
            zoomAtMousePosition: true,
            modifiers: 'ctrl',
            minScale: 0.5,
            maxScale: 3,
        },
        connecting: {
            snap: true,
            allowBlank: false,
            allowLoop: false,
            highlight: true,
            router: {
                name: 'manhattan',       //连接线根据位置自动换节点
                args: {
                    padding: 1,
                },
            },
            connector: {
                name: 'rounded',
                args: {
                    radius: 8,
                },
            },
            anchor: 'center',
            connectionPoint: 'anchor',
            allowBlank: false,
            snap: {
                radius: 20,
            },
            createEdge() {
                return new X6.Shape.Edge({
                    attrs: {
                        line: {
                            stroke: '#A2B1C3',
                            strokeWidth: 2,
                            targetMarker: {
                                name: 'block',
                                width: 12,
                                height: 8,
                            },
                        },
                    },
                    zIndex: 0,
                })
            },
            validateConnection({targetMagnet}) {
                return !!targetMagnet
            },
        },
        highlighting: {
            magnetAdsorbed: {
                name: 'stroke',
                args: {
                    attrs: {
                        fill: '#5F95FF',
                        stroke: '#5F95FF',
                    },
                },
            },
        },
        resizing: true,
        rotating: false,
        selecting: {
            enabled: true,
            rubberband: true,
            showNodeSelectionBox: true,
        },
        snapline: true,
        keyboard: true,
        clipboard: true,
        history: {
            enabled: true,
            ignoreAdd: true,
            ignoreRemove: true,
            ignoreChange: false,
        },
    })
    // #endregion

    // #region 初始化 stencil
    const stencil = new X6.Addon.Stencil({
        title: '流程图',
        target: graph,
        stencilGraphWidth: 200,
        stencilGraphHeight: 500,
        collapsable: false,
        groups: [
            {
                title: '基础流程图',
                name: 'flow',
            },
        ],
        layoutOptions: {
            columns: 1,
            columnWidth: 120,
            rowHeight: 80,
        },
    })
    document.getElementById('stencil').appendChild(stencil.container)
    // #endregion

    // #region 快捷键与事件
    // copy cut paste
    graph.bindKey(['meta+c', 'ctrl+c'], () => {
        const cells = graph.getSelectedCells()
        if (cells.length) {
            graph.copy(cells)
        }
        return false
    })
    graph.bindKey(['meta+x', 'ctrl+x'], () => {
        const cells = graph.getSelectedCells()
        if (cells.length) {
            graph.cut(cells)
        }
        return false
    })
    graph.bindKey(['meta+v', 'ctrl+v'], () => {
        if (!graph.isClipboardEmpty()) {
            const cells = graph.paste({offset: 32})
            graph.cleanSelection()
            graph.select(cells)
        }
        return false
    })

    //undo redo
    graph.bindKey(['meta+z', 'ctrl+z'], () => {
        if (graph.history.canUndo()) {
            graph.history.undo()
        }
        return false
    })
    graph.bindKey(['meta+shift+z', 'ctrl+shift+z'], () => {
        if (graph.history.canRedo()) {
            graph.history.redo()
        }
        return false
    })

    // select all
    graph.bindKey(['meta+a', 'ctrl+a'], () => {
        const nodes = graph.getNodes()
        if (nodes) {
            graph.select(nodes)
        }
    })

    //delete
    graph.bindKey('delete', () => {
        const cells = graph.getSelectedCells()
        if (cells.length) {
            graph.removeCells(cells)
        }
    })

    // zoom
    graph.bindKey(['ctrl+1', 'meta+1'], () => {
        const zoom = graph.zoom()
        if (zoom < 1.5) {
            graph.zoom(0.1)
        }
    })
    graph.bindKey(['ctrl+2', 'meta+2'], () => {
        const zoom = graph.zoom()
        if (zoom > 0.5) {
            graph.zoom(-0.1)
        }
    })

    //鼠标浮动，删除按钮
    graph.on('node:mouseenter', ({ node }) => {
        node.addTools({
            name: 'button-remove',
            args: {
                x: 0,
                y: 0,
                offset: { x: 10, y: 10 },
            },
        })
    })
    graph.on('node:mouseleave', ({ node }) => {
        node.removeTools()
    })

    //鼠标右击事件
    graph.on('node:contextmenu', ({node}) => {
        //console.log(node.label);
        $.modal.open(node.label+'流程配置',prefix+'/prop?node_id='+node.id+"&wf_id="+id,800,520);
        //layer.msg(node.id);
    })
    //双击修改内容
    graph.on('cell:dblclick', ({cell, e}) => {
        const isNode = cell.isNode()
        const name = cell.isNode() ? 'node-editor' : 'edge-editor'
        cell.removeTool(name)
        cell.addTools({
            name,
            args: {
                event: e,
                attrs: {
                    backgroundColor: isNode ? '#EFF4FF' : '#FFF',
                },
            },
        })
    })
    //双击修改内容
    graph.on('cell:click', ({cell, e}) => {
        const isNode = cell.isNode()
        if(cell.isNode())
        {
            var node_id=cell.id;
            var config = {
                url: prefix+'/getProp',
                type: "post",
                dataType: "json",
                data: {id:node_id,wf_id:id},
                beforeSend: function () {
                },
                success: function(result) {
                    $('#commentForm').loadData(result);
                    var deal_type=result.deal_type;
                    if(deal_type=="2")
                    {
                        $("#deal_type_rate").removeAttr('disabled');
                    }
                    else
                    {
                        $("#deal_type_rate").attr('disabled',true);
                    }
                }
            };
            $.ajax(config);

            //$('#commentForm').loadForm(prefix+'/getProp?id='+node_id+"&wf_id="+id);

        }
    })


    // 控制连接桩显示/隐藏
    const showPorts = (ports, show) => {
        for (let i = 0, len = ports.length; i < len; i = i + 1) {
            ports[i].style.visibility = show ? 'visible' : 'hidden'
        }
    }
    graph.on('node:mouseenter', () => {
        const container = document.getElementById('graph-container')
        const ports = container.querySelectorAll(
            '.x6-port-body',
        )
        showPorts(ports, true)
    })
    graph.on('node:mouseleave', () => {
        const container = document.getElementById('graph-container')
        const ports = container.querySelectorAll(
            '.x6-port-body',
        )
        showPorts(ports, false)
    })

    graph.on('edge:mouseenter', ({edge}) => {
        edge.addTools([
            'source-arrowhead',
            'target-arrowhead',
            {
                name: 'button-remove',
                args: {
                    distance: -30,
                },
            },
        ])
    })
    graph.on('edge:mouseleave', ({edge}) => {
        edge.removeTools()
    })

    // #endregion

    const start = graph.createNode({
        shape: 'start-node',
        label: '开始',
        width: 60,
        height: 60,
    })

    const activity = graph.createNode({
        shape: 'activity',
        label: '人员处理节点',
        width: 100,
        height: 60,
    })

    const end = graph.createNode({
        shape: 'end-node',
        label: '结束',
        width: 60,
        height: 60,
    })

    const judge = graph.createNode({
        shape: 'gateway',
        width: 60,
        height: 60,
    })
    stencil.load([start, activity, end], 'flow')

    function changeHitory() {
        if (graph.isHistoryEnabled()) {
            graph.disableHistory()
        } else {
            graph.enableHistory()
        }
    }

    //获取连线数据
    function getJson() {
        console.log(graph.toJSON());
    }

    function before() {
        graph.undo();
    }

    function next() {
        graph.redo();
    }

    function savePng() {
        graph.toPNG((dataUri) => {
            console.log(dataUri);
            // 下载
            DataUri.downloadDataUri(dataUri, 'chart.png');
        })
    }

    function saveJson()
    {
        var jsonDataNode=graph.getNodes();
        var jsonDataEdge=graph.getEdges();

        var json=graph.toJSON();
        var jsonstr = JSON.stringify(json);
        console.log(json);

        var nodes=JSON.stringify(jsonDataNode);
        var edges=JSON.stringify(jsonDataEdge);
        console.log(jsonDataNode);
        console.log(jsonDataEdge);

        var url=prefix+"/saveDesign";
        //var data={id:id,jsonData:jsonstr};
        var data={id:id,nodes:nodes,edges:edges,jsonData:jsonstr};
        var config = {
            url: url,
            type: "post",
            dataType: "json",
            data: data,
            success: function(result) {
                if(result.code==0)
                {

                }
                layer.msg(result.msg);
            }
        };
        $.ajax(config);
    }
    loadJson();
    function loadJson()
    {
        $.getJSON(prefix+"/getJson",{id:id},function(data){
            if(data)
            {
                console.log(data);
                graph.fromJSON(data);
            }
        });
    }


    function dealTypeSelect(deal_type)
    {
        if(deal_type=="2")
        {
            $("#deal_type_rate").removeAttr('disabled');
        }
        else
        {
            $("#deal_type_rate").attr('disabled',true);
        }
    }


    function submitHandler()
    {
        if($('#node_id').val()=='')
        {
            $.modal.alertWarning("请点击选择节点！");
            return;
        }
        var url=prefix+"/saveProp";
        var data=$('#commentForm').serializeArray();
        $.operate.post(url,data);
    }

    function openCond()
    {
        if($('#node_id').val()=='')
        {
            $.modal.alertWarning("请点击选择节点！");
            return;
        }
        $.modal.open($('#node_name').val()+'流程配置',prefix+'/condition?node_id='+$('#node_id').val()+"&wf_id="+id,800,520);
    }
</script>

</body>
#end